/*
   Copyright 2011 
   
   DIFED

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package com.difed.cccam.api;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

import com.difed.cccam.api.util.StringUtils;
import com.difed.cccam.util.CustomLog;

public class ConexionImpl implements Conexion {
    
    private static final String HOME = "/";
    private static final String CLIENTES = "/clients";
    private static final String SHARED = "/shares";
    private static final String SERVIDORES = "/servers";
    
    private String host;
    private String usuario;
    private String password;

	public ConexionImpl(String host, String usuario, String password) {
        super();
        this.host = host;
        this.usuario = usuario;
        this.password = password;
    }

    @Override
    public String home() throws NoConnectionException {
        return conectar(GET_TYPE, host + HOME, usuario, password);
    }

    @Override
	public String clientes() throws NoConnectionException {
        return conectar(GET_TYPE, host + CLIENTES, usuario, password);
	}

	@Override
	public String compartido() throws NoConnectionException{
	    return conectar(GET_TYPE, host + SHARED, usuario, password);
	}

	@Override
	public String servidor() throws NoConnectionException {
	    return conectar(GET_TYPE, host + SERVIDORES, usuario, password);
	}
	
	public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    protected String conectar(int requestType, String URL, String user, String pass) throws NoConnectionException {
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 5000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        DefaultHttpClient client = new DefaultHttpClient(httpParameters);
        if ((user != null) && (pass != null)) {
            client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
        }
        HttpRequestBase method = null;
        try {
            if (requestType == POST_TYPE) {
                method = new HttpPost(URL);
            } else if (requestType == GET_TYPE) {
                method = new HttpGet(URL);
            }
        } catch (IllegalArgumentException e) {
            CustomLog.error("ConexionImpl", e.getMessage());
        }
        
        String result = null;
        if (method != null) {
            try {
                HttpResponse response = client.execute(method);
                StatusLine status = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try {
                        result = StringUtils.inputStreamToString(entity.getContent());
                    } catch (IOException e) {
                        Log.e("CCCAM", e.getMessage());
                    }
                } else {
                    Log.e("CCCAM", status.getReasonPhrase());
                }
            } catch (IOException e) {
                Log.e("CCCAM", e.getMessage());
                throw new NoConnectionException();
            }
        }
        return result;
    }
}
